<template>
  <div>
    <el-tabs v-model="tabName" type="border-card">
      <el-tab-pane name="currentDate" label="今日持仓">
        <!-- 查询按钮 -->
        <div style="margin-bottom: 10px">
          <el-date-picker size="mini" v-model="currentQueryDate"></el-date-picker>
          <el-button style="margin-left:6px;" type="primary" @click="queryToday" size="mini">查询</el-button>
        </div>
        <div v-if="dataDayisToday" style="width: 920px;" v-loading="tableDataLoading">
          <div style="display: flex;align-items: center;margin-bottom: 10px;">
            <el-input size="mini" v-model.trim="myVarietyString" placeholder="输入只想查看的品种,以中横线间隔,然后保存.例如:A-B-C"></el-input>
            <el-button style="margin-left: 8px;" type="primary" size="mini" @click="toSaveMyVariety">保存</el-button>
          </div>
          <el-table
            stripe
            border
            :data="todayRankData"
            :key="rankTableKey"
            cell-class-name="custom-cell"
          >
            <el-table-column width="80" label="品种" align="center">
              <template slot-scope="scope">
                <span style="color: #b43c3c; font-weight: 700; font-size: 14px">
                  {{ scope.row.variety_name }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="long_position"
              label="前20买单量"
              align="right"
            ></el-table-column>
            <el-table-column prop="long_diff" label="买单量变化" align="right"></el-table-column>
            <el-table-column prop="short_position" label="前20卖单量" align="right"></el-table-column>
            <el-table-column prop="short_diff" label="卖单量变化" align="right"></el-table-column>
            <el-table-column prop="net_position" label="前20净持仓" align="right"></el-table-column>
            <el-table-column label="净持仓变化" align="right">
              <template slot-scope="scope">
                <span :class="scope.row.net_diff>0?'red-text':scope.row.net_diff<0?'green-text':''">
                  <span style="margin-right:4px;">{{ scope.row.net_diff }}</span>
                  <i :class="scope.row.net_diff>0?'el-icon-top':scope.row.net_diff<0?'el-icon-bottom':'el-icon-minus'"></i>
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="仓单数量"
              prop="receipt_value"
              align="right"
            ></el-table-column>
            <el-table-column label="仓单增减" align="right">
              <template slot-scope="scope">
                <span :class="scope.row.receipt_diff > 0 ? 'red-text' : scope.row.receipt_diff < 0 ? 'green-text' : ''">
                  <span style="margin-right:4px">{{ scope.row.receipt_diff }}</span>
                  <i :class="scope.row.receipt_diff>0?'el-icon-top':scope.row.receipt_diff<0?'el-icon-bottom':'el-icon-minus'"></i>
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else>
          <el-empty description="今日暂无持仓数据"></el-empty>
        </div>
      </el-tab-pane>
      <el-tab-pane name="longDate" label="持仓一览">
        <div>
          <el-checkbox size="mini" v-model="noShowZeroPostion" @change="showZeroChange">不显示持仓为0的品种</el-checkbox>
          <span class="action-btn" @click="toCopyTableImg('leftRankView')">复制左表</span>
          <span class="action-btn" @click="toCopyTableImg('rightRankView')">复制右表</span>
        </div>
        <div v-loading="tableDataLoading" style="display: flex;flex-direction: row;justify-content: flex-start;text-align: left;overflow-x: auto;">
          <div id="leftRankView">
          <el-table stripe border :data="longRankData.slice(0,Math.ceil(longRankData.length/2))" cell-class-name="custom-cell">
            <el-table-column width="100" label="品种" align="center">
              <template slot-scope="scope">
                <span style="color: #b43c3c;font-weight: 700;font-size: 14px;">{{ scope.row.variety_name }}</span>
              </template>
            </el-table-column>
            <el-table-column v-for="item,index in longRankColumns" :prop="item.prop" :label="item.label" :key="index" width="100px" align="center" class-name="custom-column"></el-table-column>
          </el-table>
          </div>
          <div style="margin-left: 5px;" id="rightRankView">
          <el-table stripe border :data="longRankData.slice(Math.ceil(longRankData.length/2))" cell-class-name="custom-cell">
            <el-table-column width="100" label="品种" align="center">
              <template slot-scope="scope">
                <span style="color: #b43c3c;font-weight: 700;font-size: 14px;">{{ scope.row.variety_name }}</span>
              </template>
            </el-table-column>
            <el-table-column v-for="item,index in longRankColumns" :prop="item.prop" :label="item.label" :key="index" width="100px" align="center"></el-table-column>
          </el-table>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="rankDataView" label="持仓可视化">
        <div v-loading="tableDataLoading">
          <!-- 选择品种 -->
          <div>
            <span>
            <el-select filterable ref="chartVarietySelect" v-model="chartSelectVariety" size="mini">
              <el-option v-for="item,index in varietyList" :value="item.variety_en" :label="item.variety_long_name" :key="index"></el-option>
            </el-select>
            </span>
            <span style="margin-left: 8px;">
              <el-date-picker style="width:220px;" type="daterange" size="mini" :clearable="false" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" v-model="chartDateRange"></el-date-picker>
            </span>
            <span style="margin-left: 8px;"><el-button type="primary" size="mini" @click="queryChartRankData">查询</el-button></span>
            <span style="margin-left: 8px;"><el-button type="success" size="mini" @click="toCopyTableImg('rankChart')">复制图形</el-button></span>
          </div>
          <!-- 显示数据图形 -->
          <el-card style="margin: 10px 0;max-width: 750px;">
            <div style="height: 400px;" id="rankChart">
              <vab-chart ref="positionChart" autoresize theme="vab-echarts-theme" :option="rankChartoption"></vab-chart>
            </div>
          </el-card>
          <!-- 显示数据表 -->
          <div style="width: 750px;">
            <el-table border stripe :data="rankChartData" cell-class-name="custom-cell">
              <el-table-column prop="quote_date" label="日期" width="100"></el-table-column>
              <el-table-column prop="variety_name" label="品种"></el-table-column>
              <el-table-column prop="long_position" label="多单量"></el-table-column>
              <el-table-column prop="short_position" label="空单量"></el-table-column>
              <el-table-column prop="net_position" label="净多单"></el-table-column>
              <el-table-column prop="net_diff" label="净多单变化"></el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import html2canvas from 'html2canvas'
  import VabChart from '@/plugins/echarts'
  import { getRuizyVariety } from '@/api/variety'
  import {
    getRankHolding,
    getVarietyReceipt,
  } from '@/api/analysisData/rankHolding'
  import { datetimeToStr } from '@/utils/datetimeUtils'
  import { saveStorageData, getStorageData } from '@/utils/storageHandler'
  export default {
    components: {
      // 此处控制台echarts会有一个无法获取DOM宽高的警告，这是因为el-tab-pane display:none所致。但vue-echarts可autoresize,设置一个高度即可
      VabChart,
    },
    data() {
      return {
        tableDataLoading: false,
        tabName: 'currentDate',
        currentQueryDate: new Date(), // 查询的持仓日期
        dataDayStr: '',
        dataDayisToday: false,
        myVarietyString: '',
        myVarietyList: [],
        varietyStorageKey: 'rankPostionHolding',
        todayRankData: [],
        rankTableKey: 0,
        longRankData: [],
        longRankColumns: [],
        noShowZeroPostion: false,

        varietyList: [],
        chartSelectVariety: '',
        chartDateRange: [],
        rankChartData: [],
        rankChartoption: {
          title: {text: '图形标题'},
          grid: {
            top: '16%',
            left: '2%',
            right: '4%',
            bottom: '35',
            containLabel: true,
          },
          toolbox: {
            show: false,
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              dataView: { readOnly: false },
              saveAsImage: {}
              }
            },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: [
            {
              type: 'category',
              /*boundaryGap: false,*/
              data: [],
              axisTick: {
                alignWithLabel: true,
              }
            },
          ],
          yAxis: [
            {
              type: 'value',
              name: '多空量',
              position: 'left',
              scale: true,
              min: null,
              max: null
            },
            {
              type: 'value',
              name: '净多单',
              position: 'right',
              min: null,
              max: null,
              splitLine:{
                show: false
              }
            },
          ],
          series: [
            {
              name: '多单量',
              type: 'line',
              symbol: 'none',
              data: [],
            },
            {
              name: '空单量',
              type: 'line',
              symbol: 'none',
              data: []
            },
            {
              name: '净多单',
              type: 'bar',
              yAxisIndex: 1,
              data: []
            }
          ],
          legend: {
            width: 750,
            bottom: 0,
            data: [{name: '多单量'}, {name: '空单量'},{name: '净多单'}]
          }
        },
        pickerOptions: {
          shortcuts: [{
            text: '近1个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '近3个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '近6个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
              picker.$emit('pick', [start, end]);
            }
          },]
        },
      }
    },
    watch: {
      tabName() {
        if (this.tabName === 'currentDate') {
          this.queryToday()
        } else if (this.tabName === 'longDate') {
          this.queryLongRank()
        } else if (this.tabName === 'rankDataView') {
          this.queryChartRankData()
        }
      },
    },
    mounted() {
      const myVariety = getStorageData(this.varietyStorageKey)
      if (myVariety){
        this.myVarietyString = myVariety
        // this.myVarietyList = myVariety.split('-')
      }

      // 设置图形选择的默认时间
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      this.chartDateRange = [start, end]

      this.queryToday()
      this.getSystemVariety()

    },
    methods:{
      // 复制持仓一览左表和图形
      toCopyTableImg(eleId){
        let table = document.getElementById(eleId)
        html2canvas(table, {backgroundColor: '#ffffff'})
        .then(canvas => {
          // console.log(canvas);
          // 将canvas转为blob对象
          canvas.toBlob((blob) => {
            // 将blob对象放入剪切板item中
            // eslint-disable-next-line no-undef
            const data = [new ClipboardItem({ [blob.type]: blob })];
            // 写入剪切板,成功会执行resolve,失败则走reject
            navigator.clipboard.write(data).then(() => {
              this.$message({
                message: '截图已保存到粘贴板',
                type: 'success',
                duration: 2000,
              });
            }, () => {
              this.$message({
                message: '保存截图失败',
                type: 'warning',
                duration: 2000,
              });
            });
          }, 'image/png');
        })
      },

      // 查询品种
      getSystemVariety(){

        getRuizyVariety({space: 'V00'}).then(res => {
          this.varietyList = res.data
          if (this.varietyList.length > 0){
            this.chartSelectVariety = this.varietyList[0].variety_en
          }
        })
      },

      // 查询仓单数量
      queryReceipt() {
        const qDate = datetimeToStr(this.currentQueryDate, true, '')
        getVarietyReceipt(qDate, qDate).then((res) => {
          const receiptData = res.data.receipt_data
          const newRankData = this.todayRankData.map((i) => {
            for (let j = 0; j < receiptData.length; j++) {
              const receipt = receiptData[j]
              if (i.variety_en === receipt.variety_en) {
                i.receipt_value = receipt.receipt
                i.receipt_diff = receipt.increase
                break
              }
            }
            return i
          })
          this.todayRankData = newRankData
          this.rankTableKey = new Date().getTime()
        })
      },

      // 查询今日持仓数据
      queryToday() {
        const params = {
          start_date: datetimeToStr(this.currentQueryDate, true, '-'),
          end_date: datetimeToStr(this.currentQueryDate, true, '-')
        }
        this.tableDataLoading = true
        getRankHolding(params).then((res) => {
          const rankData = res.data.rank_data
          if (rankData.length > 0) {
            this.dataDayStr = rankData[0].quote_date
          } else {
            this.dataDayStr = ''
          }
          if (this.myVarietyString.length > 0) {
            this.myVarietyList = this.myVarietyString.split('-')
            this.todayRankData = rankData.filter((item) => {
              return this.myVarietyList.indexOf(item.variety_en) > -1
            })
          } else {
            this.todayRankData = rankData
          }
          this.dataDayisToday = params.start_date === this.dataDayStr
          this.tableDataLoading = false
          this.queryReceipt()
        })
      },

      // 保存只查看的品种
      toSaveMyVariety(){
        saveStorageData(this.myVarietyString, this.varietyStorageKey)
        this.$baseMessage("保存我的品种成功!", 'success')
      },

      // 获取持仓变化的品种索引
      getItemIndexIn(varietyEn){
        let index = -1
        for (let i=0;i<this.longRankData.length;i++){
          if (this.longRankData[i].variety_en == varietyEn){
            index = i
            break
          }
        }
        return index
      },

      // 查询近一个月持仓情况
      queryLongRank(){
        const params = {
          start_date: datetimeToStr(new Date().setMonth(new Date().getMonth() - 1), true, '-'),
          end_date: datetimeToStr(new Date(), true, '-')
        }
        this.tableDataLoading = true
        getRankHolding(params).then(res => {
          this.longRankData = []
          this.longRankColumns = []
          // 处理显示的列
          const rankDateList = res.data.date_list
          for (let j=0;j<rankDateList.length;j++){
            if (j<2){
              this.longRankColumns.push({prop: rankDateList[j], label: j==0?rankDateList[j]: j + '天前'})
            }else{
              if (j % 5 == 0){
                this.longRankColumns.push({prop: rankDateList[j], label: j + '天前'})
              }
            }
          }
          // 处理显示的数据
          const rankData = res.data.rank_data
          // 数据组织开始
          for (let i=0;i<rankData.length;i++){
            let rankItem = rankData[i]
            let index = this.getItemIndexIn(rankItem.variety_en)
            if (index >-1){
              this.longRankData[index][rankItem.quote_date] = rankItem.net_position
            }else{
              let varietyItem = {
                variety_en: rankItem.variety_en, variety_name: rankItem.variety_name
              }
              varietyItem[rankItem.quote_date] = rankItem.net_position
              this.longRankData.push(varietyItem)
            }
          }
          this.tableDataLoading = false
        })
      },

      // 数据为0的持仓是否显示设置
      showZeroChange(isNoShow){
        if (isNoShow){
          const checkKey = this.longRankColumns[0].prop
          this.longRankData = this.longRankData.filter(item => {
            return item[checkKey] !== 0
          })
        }else{
          this.queryLongRank()
        }
      },

      // 查询数据可视化
      queryChartRankData(){
        if (!this.chartSelectVariety) return false
        const params = {
          v: this.chartSelectVariety,
          start_date: datetimeToStr(this.chartDateRange[0], true, '-'),
          end_date:  datetimeToStr(this.chartDateRange[1], true, '-')
        }
        this.tableDataLoading = true
        getRankHolding(params).then(res => {
          const selectVariety = this.$refs.chartVarietySelect.selectedLabel  // 获取选中的Lable名称
          const rankData = res.data.rank_data
          let chartOption = JSON.parse(JSON.stringify(this.rankChartoption))
          chartOption.title.text = selectVariety + '前20持仓量变化'
          chartOption.xAxis[0].data = rankData.map(item => {return item.quote_date })
          chartOption.series[0].data = rankData.map(item => {return item.long_position })
          chartOption.series[1].data = rankData.map(item => {return item.short_position })
          chartOption.series[2].data = rankData.map(item => {return item.net_position })
          this.$refs.positionChart.clear()
          this.rankChartoption = chartOption
          this.rankChartData = rankData
          this.tableDataLoading = false
        })
      }

    }
  }
</script>

<style scoped lang="scss">
.action-btn{
  margin-left: 10px;
  cursor: pointer;
  color: #2566ca;
  &:hover{
    color: #e20f0c;
  }
}
</style>
